<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*60);
ini_set('memory_limit', '512M');

require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
require_once dirname(__FILE__). '/util/TimeUtil.php';



$g_start = microtime(true);

$dbconn = Connection::getInstance();

//$argv[1] = '2011-11';

if(count($argv) ==  2) {
	$site = $argv[1];
}else{
	echo "Usage: php stat_ltv.php [site_id]\n";
	exit;
	$site = 'frontend.local';
}

$userInfos = getUserInfos($site, $dbconn);
$userInfos = useIdAsKey($userInfos);
traversalDirectoryFile($userInfos, RAW_DATA_ROOT);
foreach($userInfos as $k=>$v){
	if(isset($v['sessionNum'])){
		$userInfos[$k]['tokenPerSession'] = $v['credits'] / $v['sessionNum'];
	}else{
		$userInfos[$k]['tokenPerSession'] = '';
	}
//	unset($userInfos[$k]['credits']);
	unset($userInfos[$k]['sessionNum']);
	
	if(isset($v['full_reg_time'])){
		$userInfos[$k]['registrationToProfileTime'] = (($v['full_reg_time'] - $v['created']) / 60) . 'minutes' ;
	}else{
		$userInfos[$k]['registrationToProfileTime'] = '';
	}
	unset($userInfos[$k]['full_reg_time']);
	
	if(isset($v['confirmed_coreg_time'])){
		$userInfos[$k]['registrationToConfirmTime'] = (($v['confirmed_coreg_time'] - $v['created']) /60) . 'minutes';
	}else{
		$userInfos[$k]['registrationToConfirmTime'] = '';
	}
	unset($userInfos[$k]['confirmed_coreg_time']);
	
	$userInfos[$k]['created'] = date('Y-m-d H:i:s', $v['created']);
	$userInfos[$k]['last_visit'] = date('Y-m-d H:i:s', $v['last_visit']);
}
$csvHeader = array('uID', 'Publisher', 'Placement', 'Register Time', 'Last Visit', 'Gender', 'Birthday', 'Zipcode', 'Domain', 'token earned', 'won', 'token Per session', 'registration To Profile Time', 'registration To Confirm Time');
sendCsv($userInfos, $csvHeader, 'LTV_' . $site . '.csv');

echo 'Totally: '. (microtime(true) - $g_start) . " seconds \n";
echo "memory: " . memory_get_peak_usage() . " bytes \n";

function getUserInfos($site, $db) 
{
	global $g_start;
//	$sql = " SELECT u.id, u.pub, u.pla, u.created, u.last_visit, u.gender, u.birthday, u.zipcode, SUM(r.credit) AS credits, s.domain FROM users u LEFT JOIN sites s ON u.site_id=s.id LEFT JOIN rewards r ON u.id=r.user_id WHERE s.domain=? GROUP BY u.id ";
	try{
//		$result = $db->query($sql, array($site));
//		return $result;
		if ($site == 1)
		{
			$domain = 'cashdazzle.com';
		}
		else if ($site == 2)
		{
			$domain = 'lalaloot.com';
		}
		else if ($site == 3)
		{
			$domain = 'mommymoolah.com';
		}
		$sql = "select id, pub, pla, created, last_visit, gender, birthday, zipcode, ? as domain, 0 as credits, won from users where site_id=?";
		$users = $db->query($sql, array($domain, $site));
		echo "Total Users: " . count($users) . "\t" . (microtime(true) - $g_start) . "\n";
		$count = 0;
		foreach ($users as &$user)
		{
			$sql = 'select sum(credit) as credits from rewards where user_id=?';
			$result = $db->query($sql, array($user['id']));
			$user['credits'] = $result[0]['credits'];
			$count ++;
			if ($count % 10000 == 0)
			{
				echo "finished ". $count . "\t" . (microtime(true) - $g_start) . "\n";
			}
		}
		return $users;
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function useIdAsKey($arr)
{
	$ret = array();
	foreach($arr as $k=>$v){
		$ret[$v['id']] = $v;
	}
	
	return $ret;
}


function traversalDirectoryFile(&$userInfos, $path)
{
	$handle = opendir($path);
	while($file = readdir($handle)){
  		if($file=="."||$file=="..")
   		continue;
  		$newFilePath = $path . DIRECTORY_SEPARATOR . $file;
  		if(is_dir($newFilePath)){
//   			echo "document---------->".$newFilePath."<br>";
   			traversalDirectoryFile($userInfos, $newFilePath);
  		}
  		if(is_file($newFilePath)){
//  			echo "File-------------->  ".$newFilePath."<br>";
  			$file_handle = fopen($newFilePath, 'r');
  			if ($file_handle) {
				while (!feof($file_handle)) {
					$line = fgets($file_handle);
					if (!empty($line)) {
						//echo $line."<br>";
						$line_args = explode(':', $line);
						$time = isset($line_args[0])? $line_args[0] : 0;
						$session = isset($line_args[2])? $line_args[2] : '';
						$uid = isset($line_args[3])? $line_args[3] : '';
						$event = isset($line_args[4])? $line_args[4] : '';
						if(isset($userInfos[$uid])){
							if($session != ''){
								if(!isset($userInfos[$uid]['sessionNum'])){
									$userInfos[$uid]['sessionNum'] = 1;
								}else{
									$userInfos[$uid]['sessionNum']++;
								}
							}
							if($event == 'full_reg'){
								$userInfos[$uid]['full_reg_time'] = $time;
							}
							if($event == 'confirmed_coreg'){
								$userInfos[$uid]['confirmed_coreg_time'] = $time;
							}
						}
						
					}
				}
				fclose($file_handle);
			}
  		}
 	}
 	closedir($handle);
}

function sendCsv($data, $headers, $filename) {
	$output = fopen(dirname(__FILE__) . DIRECTORY_SEPARATOR . $filename, 'w');	//var_dump('output file------>' . RAW_DATA_ROOT . DIRECTORY_SEPARATOR . $filename);
	fputcsv($output, $headers);
	if(!empty($data)){
		foreach ($data as $row) {
			fputcsv($output, $row);
		}			
	}

	
	fclose($output);
}





